package com.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author hh
 * @since 2023/5/31
 */
public class CASDemo {

    public static void main(String[] args) {

        AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<Integer>(129, 1);

        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            System.out.println("线程1获得的版本号：" + stamp);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println("线程1比较转换：" + atomicStampedReference.compareAndSet(129, 2, stamp, stamp + 1));
            System.out.println("线程1转换后的版本号：" + atomicStampedReference.getStamp());
        }).start();

        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            System.out.println("线程2获得的版本号：" + stamp);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println("线程2比较转换：" + atomicStampedReference.compareAndSet(129, 2, stamp, stamp + 1));
            System.out.println("线程2转换后的版本号：" + atomicStampedReference.getStamp());
        }).start();
    }
}
